<template>
    <div class="jianzhan-content">
        <Crumb name="Service Report"/>
        <div class="content">
            <Search>
                <el-input
                        v-model="key"
                        size="small"
                        class="input"
                        placeholder="Search By Request No"
                        prefix-icon="el-icon-search"></el-input>
                <el-date-picker v-model="startTime" value-format="yyyy-MM-dd" type="date" class="input" size="small"
                                placeholder="Start time"></el-date-picker>
                <el-date-picker v-model="endTime" type="date" value-format="yyyy-MM-dd" class="input" size="small"
                                placeholder="End time"></el-date-picker>
                <el-button type="primary" size="small" @click="showTop">Top 10 Most Damage</el-button>
            </Search>
            <div class="table-wrapper">
                <el-table
                        :data="closeList.slice((pageNum-1) * pageSize,pageNum * pageSize)"
                        border
                        row-key="id"
                        stripe
                        style="width: 100%"
                >
                    <el-table-column
                            prop="requestNo"
                            label="Request Number"
                    ></el-table-column>
                    <el-table-column
                            prop="workingNo"
                            label="Working Number"
                    ></el-table-column>
                    <el-table-column
                            prop="plateNum"
                            label="plate Num"
                    ></el-table-column>

                    <el-table-column
                            label="Actual problem"
                    >
                        <template slot-scope="item">
                            <div v-for="problem in item.row.actualProblem" :key="problem.id">
                                {{problem.problemDescription}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="causeOfProblem"
                            label="Cause of problem"
                    ></el-table-column>
                    <el-table-column>
                        <template slot-scope="request">
                            <el-button size="small" @click="showDetail(request.row)">Detail</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="page">
                    <el-pagination background
                                   :page-size="pageSize"
                                   @current-change="changePage"
                                   layout="prev, pager, next"
                                   :total="total"></el-pagination>
                </div>
            </div>
        </div>

        <el-dialog title="Service Detail" :visible.sync="dialogVisible" width="100%" top="0">
            <quest-show :quest="quest"/>
            <div class="spin"></div>
            <work-order-show :work="work"/>
            <div class="spin"></div>
            <el-form label-width="150px">
                <div style="display: flex">
                    <div class="flex-content">
                        <el-form-item label="Actual Problem" v-if="close.problemVoList">
                            <div class="problem" v-for="(item,index) in close.problemVoList" :key="index"
                                 style="position: relative;margin-bottom: 10px;">
                                <div>
                                    <h4 class="title">{{item.problemDescription}}</h4>
                                    <div v-if="item.problemPhoto">
                                        <div v-for="photo in item.problemPhoto" :key="photo">
                                            {{photo}}
                                        </div>
                                    </div>
                                    <div v-if="item.problemVideo">
                                        <div v-for="photo in item.problemVideo" :key="photo">
                                            {{photo}}
                                        </div>
                                    </div>
                                    <div v-if="item.problemFile">
                                        <div v-for="photo in item.problemFile" :key="photo">
                                            {{photo}}
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </el-form-item>

                        <el-form-item label="Cause of problem">
                            <span>{{close.causeOfProblem}}</span>
                        </el-form-item>

                        <el-form-item label="Action">
                            <div class="problem" v-for="(item,index) in close.suggestionVoList" :key="index"
                                 style="position: relative;margin-bottom: 10px;">
                                <div>
                                    <h4 class="title">{{item.suggestion}}</h4>
                                    <div v-if="item.photo">
                                        <div v-for="photo in item.photo" :key="photo">
                                            {{photo}}
                                        </div>
                                    </div>
                                    <div v-if="item.video">
                                        <div v-for="photo in item.video" :key="photo">
                                            {{photo}}
                                        </div>
                                    </div>
                                    <div v-if="item.file">
                                        <div v-for="photo in item.file" :key="photo">
                                            {{photo}}
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </el-form-item>
                    </div>
                    <div class="flex-content">
                        <el-form-item label="Remarks">
                            {{close.remarks}}
                        </el-form-item>

                    </div>
                    <div class="flex-content">
                        <el-form-item label="End Date">
                            {{work.createTime}}
                        </el-form-item>
                        <el-form-item label="Hand Over">
                            {{close.handOverName}}
                        </el-form-item>
                    </div>
                </div>
            </el-form>
            <div class="spin"></div>
            <el-table
                    height="200"
                    :data="pointCodeList"
                    style="width: 100%">
                <el-table-column
                        prop="category"
                        label="category"
                >
                </el-table-column>
                <el-table-column
                        prop="description"
                        label="description"
                >
                </el-table-column>
                <el-table-column
                        prop="hours"
                        label="hours">
                </el-table-column>
                <el-table-column
                        prop="pointCode"
                        label="pointCode">
                </el-table-column>
                <el-table-column
                        prop="unit"
                        label="unit">
                </el-table-column>
                <el-table-column

                >
                    <template slot-scope="scope">
                        <el-button type="danger" icon="el-icon-delete" @click="deletePointCode(scope.row)"></el-button>
                    </template>
                </el-table-column>

            </el-table>
            <spDataBase @deleteItem="deleteItem" :partList="partList"/>
            <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">Cancel</el-button>
                        <el-button type="primary" @click="submitForm">Confirm</el-button>
                    </span>
        </el-dialog>
        <el-dialog
                title="Most damage"
                :visible.sync="showTopDialog"
                width="100%"
        >
            <el-table
                    :data="plateNumDamageList"
                    stripe
                    border
                    style="width: 100%">
                <el-table-column
                        prop="brand"
                        label="Brand"
                >
                </el-table-column>
                <el-table-column
                        prop="equipmentType"
                        label="Type"
                >
                </el-table-column>
                <el-table-column
                        prop="model"
                        label="Model"
                >
                </el-table-column>
                <el-table-column
                        prop="plateNum"
                        label="Plate No"
                >
                </el-table-column>
                <el-table-column
                        prop="sn"
                        label="Sn"
                >
                </el-table-column>

            </el-table>
            <el-table
                    :data="categoryDamageList"
                    border
                    stripe
                    style="width: 100%;margin-top: 30px;">
                <el-table-column
                        label="category"
                >
                    <template slot-scope="item">
                        {{item.row}}
                    </template>
                </el-table-column>
            </el-table>

            <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="showTopDialog = false">Close</el-button>
          </span>
        </el-dialog>

        <Part-item @close="dbVisible = false" @add="add" :visible="dbVisible"/>

    </div>
</template>

<script>
    import Crumb from '@/components/common/crumb'
    import Search from '@/components/common/search'
    import spDataBase from '@/components/part/spDataBase'
    import PartItem from '@/components/part/sparePartItem'
    import questShow from '@/components/service/questShow'
    import {getAllReport, closeOrder, getOrder, getTopTen} from "../../api/service";
    import {ERROR_OK} from "../../util/config";
    import mixins from '../../util/mixins'
    import dbMixins from '../../util/spMixins'
    import WorkOrderShow from "../../components/service/workOrderShow";

    const files = [{
        problemDescription: '',
        problemPhoto: [],
        problemVideo: [],
        problemFile: []
    }];
    const quest = {
        requestNo: '',
        requestDate: '',
        initiator: '',
        customerId: '',
        customerName: '',
        addressId: '',
        address: '',
        distance: '',
        unitModel: '',
        sn: '',
        deliveryTime: '',
        hmKm: '',
        typeCode: '',
        serviceType: "",
        appointmentTime: '',
        note: '',
        status: "",
        projectName: '',
        plateNum: '',
        charges: [],
        reason: '',
        problems: [...files],
        id: '',
    };
    export default {
        name: "close-order",
        mixins: [mixins, dbMixins],
        data() {
            return {
                key: '',
                startTime: '',
                endTime: '',
                close: {
                    recommendationList: [{sn: '', description: ''}],
                    problemVoList: [...files],
                    suggestionVoList: [{suggestion: '', problemPhoto: [], problemVideo: [], problemFile: []}],
                    remarks: ''

                },
                pointCodeList:[],
                quest: {...quest},
                work: {
                    workingNo: '',
                    woStatus: 2,
                    arrangedBy: '',
                    suratJalanNo: '',
                    salesOrderNo: '',
                    workingPlace: '',
                    continueWoReason: '',
                    continueWoDate: '',
                    continueWoNo: '',
                    date: '',
                    jobReceiver: [{receiverId: ''}]
                },
                list: [],
                dialogVisible: false,
                woStatus: [{key: 0, value: 'On Progress'}, {key: 1, value: 'Wait for spareparts'}, {
                    key: 2,
                    value: 'Reschedule'
                }, {key: 3, value: 'Finished'}, {key: 4, value: 'Job Continue'}],
                fileShow1: false,
                fileShow2: false,
                picture: [],
                video: [],
                file: [],
                showTopDialog: false,
                plateNumDamageList: [],
                categoryDamageList: []
            }
        },
        computed: {
            closeList() {
                return this.list.filter(item => item.requestNo.indexOf(this.key) > -1)
            }
        },
        created() {
            this._getCloseList();
        },
        methods: {
            async submitForm() {
                let problem = this.close.problemVoList;
                const newProblem = [];
                problem.forEach(item => {
                    newProblem.push({
                        problemDescription: item.problemDescription,
                        problemPhoto: item.problemPhoto ? item.problemPhoto.join(',') : '',
                        problemFile: item.problemFile ? item.problemFile.join(',') : '',
                        problemVideo: item.problemVideo ? item.problemVideo.join(',') : ''
                    })
                });
                const recommendation = JSON.stringify(this.close.recommendation);
                let suggestion = this.close.suggestionVoList;
                const newSuggestion = [];
                suggestion.forEach(item => {
                    newSuggestion.push({
                        suggestion: item.suggestion,
                        photo: item.problemPhoto ? item.problemPhoto.join(',') : '',
                        video: item.problemVideo ? item.problemVideo.join(',') : '',
                        file: item.problemFile ? item.problemFile.join(',') : ''
                    })
                });
                let sparePartsList = this.partList.map(part => {
                    return {
                        partsId: part.id,
                        partsQuantity: part.number,
                        workOrderNum: this.work.workingNo
                    }
                });
                const {orderId} = this.work;
                const {remarks} = this.close
                sparePartsList = JSON.stringify(sparePartsList);
                const {status} = await closeOrder({
                    orderId,
                    remarks,
                    recommendation,
                    problem: JSON.stringify(newProblem),
                    suggestion: JSON.stringify(newSuggestion),
                    depletes: sparePartsList
                });
                if (status === ERROR_OK) {
                    this.$message.success('Success');
                    this.dialogVisible = false;
                    this._getCloseList();
                    this.clear();
                }
            },
            async _getCloseList() {
                const {status, data} = await getAllReport();
                if (status === ERROR_OK) {
                    this.list = data;
                    this.total = data.length
                }
            },
            async _getOrder(workingNo) {
                const {status, data} = await getOrder(workingNo);
                if (status === ERROR_OK) {
                    this.close = data.workingOrderVo;
                    this.work = data.workingOrderVo;
                    this.$set(this.work, 'jobReceiver', data.workingOrderVo.jobReceiverVoList);
                    this.partList = data.workingOrderVo.partsList.map(part => {
                        return {
                            ...part,
                            number: part.quantity,
                            quantity: part.sparePartsStock,
                        }
                    });
                    this.pointCodeList = data.workingOrderVo.serviceChargeList
                    this.quest = data.orderDetailVo.orderVo;
                    if (data.orderDetailVo.problemVoList.length) {
                        this.$set(this.quest, 'problems', data.orderDetailVo.problemVoList);
                    } else {
                        this.$set(this.quest, 'problems', [{
                            problemDescription: '',
                            problemPhoto: [],
                            problemVideo: [],
                            problemFile: []
                        }])
                    }
                }
            },
            async showTop() {
                if (!this.startTime) {
                    this.$notify.error('Please Select Start time');
                    return
                }
                if (!this.endTime) {
                    this.$notify.error('Please Select End time');
                    return
                }
                const {status, data, msg} = await getTopTen(this.startTime, this.endTime);
                if (status === ERROR_OK) {
                    this.showTopDialog = true;
                    this.plateNumDamageList = data.plateNumList;
                    this.categoryDamageList = data.categoryList
                } else {
                    this.$notify.error(msg)
                }
            },
            showDetail(work) {
                this._getOrder(work.workingNo);
                this.dialogVisible = true;
            },
        },
        components: {
            WorkOrderShow,
            Crumb, Search, spDataBase, PartItem, questShow
        },
        watch: {
            workList(list) {
                this.total = list.length
            }
        }
    }
</script>

<style scoped lang="scss">
    @import "../../css/mixins";

    .content {
        @include content
    }

    .spin {
        border-bottom: 2px dashed #ddd;
        width: 100%;
        height: 0;
        margin-top: 20px;
    }
</style>